﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MyWebUI1
{
    public class SiteUtil
    {
        #region Cookie Helper
        /// <summary>
        /// 从客户端cookie中取得单个字符串数据
        /// </summary>
        /// <param name="key">Cookie的名字</param>
        /// <returns>返回的cookie值</returns>
        public static string GetString(string key)
        {
            if (string.IsNullOrEmpty(key))
            {
                return null;
            }

            if (HttpContext.Current.Request.Cookies[key] != null)
            {
                return HttpContext.Current.Request.Cookies[key].Value;
            }

            return null;
        }

        /// <summary>
        /// 向客户端Cookie写入单个字符串值。缺省的有效期为30天
        /// </summary>
        /// <param name="key">要写入的Cookie的名字</param>
        /// <param name="value">要写入的Cookie的值</param>
        public static void SetString(string key, string value)
        {
            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentNullException("key", "Cookie 名称不能为空");
            }

            HttpCookie cookie = new HttpCookie(key, value);
            //cookie.Expires = DateTime.Now.AddDays(30);

            HttpContext.Current.Response.Cookies.Add(cookie);
        }

        /// <summary>
        /// 向客户端Cookie写入单个字符串值。缺省的有效期为30天
        /// </summary>
        /// <param name="key">要写入的Cookie的名字</param>
        /// <param name="value">要写入的Cookie的值</param>
        /// <param name="expireDays"></param>
        public static void SetString(string key, string value, int expireDays)
        {
            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentNullException("key", "Cookie 名称不能为空");
            }

            HttpCookie cookie = new HttpCookie(key, value);
            cookie.Expires = DateTime.Now.AddDays(expireDays);

            HttpContext.Current.Response.Cookies.Add(cookie);
        }

        #endregion



    }
}
